<template>
  <div class="app-container">
    <div>
      <el-row>
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="120px">
          <el-form-item label="登录名称" prop="username" class="search-item">
            <el-input v-model.trim="queryParams.username" placeholder="请输入登录名称" class="search-input" clearable size="small" style="width: 240px" @blur="onSearchUsernameBlurEvent" />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile" class="search-item">
            <el-input v-model.trim="queryParams.mobile" placeholder="请输入手机号码" class="search-input" clearable size="small" style="width: 240px" />
          </el-form-item>
          <el-form-item label="状态" prop="status" class="search-item">
            <el-select v-model="queryParams.status" placeholder="用户状态" class="search-input" clearable size="small" style="width: 240px">
              <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-col :span="24">
            <el-form-item label=" ">
              <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-setting" size="small" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button v-hasPermi="['system:user:add']" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-hasPermi="['system:user:edit']" type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-hasPermi="['system:user:remove']" type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <right-toolbar :show-search.sync="showSearch" :columns="columns" @queryTable="getList" />
      </el-row>

      <el-table v-loading="loading" :data="userList" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column v-if="columns[0].visible" key="id" label="用户编号" align="center" prop="id" />
        <el-table-column v-if="columns[1].visible" key="username" label="登录名称" align="center" prop="username" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[2].visible" key="nickname" label="用户姓名" align="center" prop="nickname" :show-overflow-tooltip="true" />
        <el-table-column v-if="columns[3].visible" key="mobile" label="手机号码" align="center" prop="mobile" width="120" />
        <el-table-column v-if="columns[4].visible" key="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" :disabled="scope.row.id == 1" active-value="Y" inactive-value="N" @change="handleStatusChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="180" class-name="small-padding fixed-width">
          <template v-if="scope.row.id !== 1" slot-scope="scope">
            <el-button v-hasPermi="['system:user:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-hasPermi="['system:user:remove']" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-dropdown v-hasPermi="['system:user:resetPwd', 'system:user:edit']" size="mini" @command="(command) => handleCommand(command, scope.row)">
              <span class="el-dropdown-link">
                <i class="el-icon-d-arrow-right el-icon--right" />更多
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-hasPermi="['system:user:resetPwd']" command="handleResetPwd" icon="el-icon-key">重置密码</el-dropdown-item>
                <el-dropdown-item v-hasPermi="['system:user:edit']" command="handleAuthRole" icon="el-icon-circle-check">分配角色</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNumber" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="nickname">
              <el-input v-model.trim="form.nickname" class="search-input" placeholder="请输入用户姓名" maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model.trim="form.mobile" class="search-input" placeholder="请输入手机号码" maxlength="11" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.id == undefined" label="登录名称" prop="username">
              <el-input v-model.trim="form.username" class="search-input" placeholder="请输入登录名称" maxlength="20" show-word-limit @blur="onEditUsernameBlurEvent" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.id == undefined" label="登录密码" prop="password">
              <el-input v-model.trim="form.password" class="search-input" placeholder="请输入登录密码" type="password" auto-complete="new-password" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择" class="search-input">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status == 'N'" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" :rows="4" class="mult-text" type="textarea" placeholder="请输入内容" maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus } from '@/api/system/user'
import { listNormalRole } from '@/api/system/role'
export default {
  name: 'User',
  dicts: ['sys_normal_disable'],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNumber: 1,
        pageSize: 10,
        username: undefined,
        mobile: undefined,
        status: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `登录名称`, visible: true },
        { key: 2, label: `用户姓名`, visible: true },
        { key: 3, label: `手机号码`, visible: true },
        { key: 4, label: `状态`, visible: true },
        { key: 5, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        username: [
          { required: true, message: '登录名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '登录名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '用户姓名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '登录密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '登录密码长度必须介于 6 和 20 之间', trigger: 'blur' }
        ],
        mobile: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getList()
  },
  methods: {
    onSearchUsernameBlurEvent (event) {
      if (this.queryParams.username) {
        this.queryParams.username = this.queryParams.username.toLowerCase()
      }
    },
    onEditUsernameBlurEvent (event) {
      if (this.form.username) {
        this.form.username = this.form.username.toLowerCase()
      }
    },
    /** 查询用户列表 */
    getList () {
      this.loading = true
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.data.records
        this.total = response.data.total
        this.loading = false
      }
      )
    },
    // 用户状态修改
    handleStatusChange (row) {
      const text = row.status === 'Y' ? '启用' : '停用'
      this.$modal.confirm('确认要"' + text + '""' + row.username + '"用户吗？').then(function () {
        return changeUserStatus(row.id, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function () {
        row.status = row.status === 'Y' ? 'N' : 'Y'
      })
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,
        username: undefined,
        nickname: undefined,
        password: undefined,
        mobile: undefined,
        status: 'Y',
        remark: undefined,
        roleIds: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNumber = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand (command, row) {
      switch (command) {
        case 'handleResetPwd':
          this.handleResetPwd(row)
          break
        case 'handleAuthRole':
          this.handleAuthRole(row)
          break
        default:
          break
      }
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      listNormalRole().then(response => {
        this.roleOptions = response.data
        this.open = true
        this.title = '添加用户'
      })
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      if (row.id === 1 || (this.ids && this.ids.indexOf(1) > -1)) {
        this.$modal.msgError('超级管理员不能修改')
        return
      }
      this.reset()
      const userId = row.id || this.ids
      getUser(userId).then(response => {
        this.form = response.data
        this.roleOptions = response.data.roles
        this.form.roleIds = response.data.roleIds
        this.open = true
        this.title = '修改用户'
        this.form.password = ''
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd (row) {
      this.$prompt('请输入"' + row.username + '"的新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^.{6,20}$/,
        inputErrorMessage: '登录密码长度必须介于 6 和 20 之间'
      }).then(({ value }) => {
        resetUserPwd(row.id, value).then(response => {
          this.$modal.msgSuccess('修改成功，新密码是：' + value)
        })
      }).catch(() => { })
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.id
      this.$router.push('/system/user-auth/role/' + userId)
    },
    /** 提交按钮 */
    submitForm: function () {
      const that = this
      that.$refs['form'].validate(valid => {
        if (valid) {
          if (that.form.id !== undefined) {
            delete that.form.username
            delete that.form.password
            updateUser(that.form).then(response => {
              that.$modal.msgSuccess('修改成功')
              that.open = false
              that.getList()
            })
          } else {
            addUser(that.form).then(response => {
              that.$modal.msgSuccess('新增成功')
              that.open = false
              that.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      if (row.id === 1 || (this.ids && this.ids.indexOf(1) > -1)) {
        this.$modal.msgError('超级管理员不能删除')
        return
      }
      const userIds = row.id || this.ids
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
        return delUser(userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => { })
    }
  }
}
</script>
